package com.ls.blog.service;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.ls.blog.exception.TokenExpiredException;
import com.ls.blog.exception.TokenNotFoundException;
import com.ls.blog.exception.TokenParseException;
import com.ls.blog.api.TokenService;
import com.ls.blog.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @program: myblog
 * @author: lishun
 * @create: 2021-07-09 09:46
 **/
@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public UserInfo tokenParse(String token) throws Exception{
        // 执行认证
        if (token == null) {
            throw new TokenNotFoundException("没有发现token信息");
        }
        // 获取 token 中的 user id
        String userId;

        // 验证token是否能解析
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new TokenParseException("token解析失败");
        }
        log.info("token开始从redis中查询---------------------------------------------------->");
        long startTime = System.currentTimeMillis();
        // redis中匹配
        String userInfo = redisTemplate.opsForValue().get("TOKEN_" + token);
        long endTime = System.currentTimeMillis();
        log.info("共运行" + (endTime-startTime));
        log.info("token开始查询结束--------------------------------------->");
        if (userInfo==null){
            throw new TokenExpiredException("token过期");
        }
        UserInfo info = JSON.parseObject(userInfo, UserInfo.class);
        return info;
    }
}
